package org.csq.controller;

import org.csq.controller.dto.DeleteByIdsRequest;
import org.csq.controller.dto.GetDataRequest;
import org.csq.entity.PageResult;
import org.csq.entity.Result;
import org.csq.entity.SaveDataRequest;
import org.csq.service.MetadataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/easyDisplay")
public class EasyDisplayController {

    @Autowired
    private MetadataService metadataService;

    @GetMapping("/metadata/{tableName}")
    public Result<List<Map<String, Object>>> metadata(@PathVariable("tableName") String tableName) {
        try {
            List<Map<String, Object>> result = metadataService.getMetadataByTableName(tableName);
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "服务器内部错误");
        }
    }

    @PostMapping("/getData")
    public Result<PageResult> getData(@RequestBody GetDataRequest request) {
        try {
            PageResult result = metadataService.getDataByTableName(
                    request.getTableName(),
                    request.getQuery(),
                    request.getPage()
            );
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "服务器内部错误");
        }
    }

    @PostMapping("/saveData")
    public Result<Map<String, Object>> saveData(@RequestBody SaveDataRequest request) {
        try {
            Map<String, Object> result = metadataService.saveData(
                    request.getTableName(),
                    request.getData()
            );
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "服务器内部错误：" + e.getMessage());
        }
    }

    @PostMapping("/deleteByIds")
    public Result<Integer> deleteByIds(@RequestBody DeleteByIdsRequest request) {
        try {
            Integer count = metadataService.deleteByIds(request.getTableName(), request.getIds());
            return Result.success(count);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "服务器内部错误：" + e.getMessage());
        }
    }
}
